import { BaseContext } from 'koa';
import { getRepository, Repository,  } from "typeorm";
import { loginUtil } from "../../utils/login";
import { User } from "../../database/entity/user";

export default class LoginControl {

    public static async login (ctx: BaseContext) {
        // const expiresIn =  Math.floor(Date.now() / 1000) + 24 * 60 * 60 // 一天;

        const name: string = ctx.query.name;
        const password: string = ctx.query.password;
        await loginUtil(ctx,name,password);
    }

    public static async logout (ctx: BaseContext) {
        const name: string = ctx.query.name;

        const userRepository: Repository<User> = getRepository(
            User
        );
        const user: User = await userRepository.findOne({
            name,
        });
        user.token = "";
        if(user) {
            if (!(await userRepository.findOne({id: user.id}))) {
                ctx.status = 400;
                ctx.app.emit('error',{
                    code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                    message: ctx.ERROR.ERRORMSG_NOUSER,
                },ctx);
            }else {
                await userRepository.save(user);
                ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_LOGOUTSUCCESS,{});
            }
        }else {
            ctx.app.emit('error',{
                code: ctx.ERROR.ERRORCODE_NOUSER,
                message: ctx.ERROR.ERRORMSG_NOUSER,
            },ctx);
        }
    }

}